import json
import random
import re

from django_redis import get_redis_connection
from ronglian_sms_sdk import SmsSDK

accId = '2c94811c946f6bfb0196ec77d1197904'
accToken = '8cfe4ba3c0bf473fa8ceec75cfdabaf5'
appId = '2c94811c946f6bfb0196ec77d2b0790b'

def send_message(phone):
    sdk = SmsSDK(accId, accToken, appId)
    tid = '1'
    # 保存到Redis前先验证手机号格式
    if not re.match(r'^1[3-9]\d{9}$', phone):
        return json.dumps({'statusCode': '400', 'message': '手机号格式错误'})
    clinet =  get_redis_connection('sms_code')
    d = random.randint(0000,9999)
    # 保存到redis中,有效期300s
    clinet.setex(phone, 300, str(d))
    datas = (d, '5')
    resp = sdk.sendMessage(tid, phone, datas)
    return resp

